﻿using System;
using System.IO;
using System.Media;
using System.Net;
using System.Windows;
using System.Windows.Media.Imaging;

namespace BeerManagementSystem
{
    internal class UriConnector
    {
        private string _baseDirectory;
        private SoundPlayer _player;
        private static UriConnector _instance;
        GameCdSound gameCdSound;

        public static UriConnector Instance
        {
            get { return _instance ?? (_instance = new UriConnector()); }
        }

        private  UriConnector ()
        {
            //TODO sollte später aus config ausgelesen werden
            _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
            _player =new SoundPlayer();
            
        }

        public string UserImagePath 
        {
            get
            {
                return (Properties.Settings.Default.UserImagePath == "")
                             ? _baseDirectory + "AppData" + Path.DirectorySeparatorChar + "UserImages" +
                               Path.DirectorySeparatorChar
                             : Properties.Settings.Default.UserImagePath + Path.DirectorySeparatorChar;
            }
        }

        public string DoctorImagePath
        {
            get
            {
                return (Properties.Settings.Default.DoctorImagePath == "")
                             ? _baseDirectory + "AppData" + Path.DirectorySeparatorChar + "DocterImages" +
                               Path.DirectorySeparatorChar
                             : Properties.Settings.Default.DoctorImagePath + Path.DirectorySeparatorChar;
            }
        }

        public string SoundsPath
        {
            get
            {
                return (Properties.Settings.Default.DoctorImagePath == "")
                             ? _baseDirectory + "AppData" + Path.DirectorySeparatorChar + "Sounds" +
                               Path.DirectorySeparatorChar
                             : Properties.Settings.Default.SoundsPath + Path.DirectorySeparatorChar;
            }
        }

        public string LogPath
        {
            get
            {
                return (Properties.Settings.Default.DoctorImagePath == "")
                             ? _baseDirectory + "AppData" + Path.DirectorySeparatorChar + "log" +
                               Path.DirectorySeparatorChar
                             : Properties.Settings.Default.LogPath + Path.DirectorySeparatorChar;
            }
        }

        public string MessageImagePath
        {
            get
            {
                return (Properties.Settings.Default.UserImagePath == "")
                             ? _baseDirectory + "AppData" + Path.DirectorySeparatorChar + "MessageImages" +
                               Path.DirectorySeparatorChar
                             : Properties.Settings.Default.MessageImagePath + Path.DirectorySeparatorChar;
            }
        }

        public BitmapImage GetProfileImage(User user)
        {
            var bild = new BitmapImage();

            try
            {
                bild.BeginInit();
                bild.CacheOption = BitmapCacheOption.OnLoad;
                bild.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                bild.UriSource = new Uri(UserImagePath + user.FirstName + "_" + user.LastName + ".jpg",
                                         UriKind.Absolute);
                bild.EndInit();

                return bild;

            }
            catch (InvalidOperationException invalidOperation)
            {
                LogWriter.WriteError("[Line: 36]" + invalidOperation.Message + "\n");
                LogWriter.WriteMessage(invalidOperation.StackTrace + "\n");
            }
            catch (ArgumentException argumentException)
            {
                LogWriter.WriteError("[Line: 39]" + argumentException + "\n");
            }
            catch (UriFormatException uriFormatException)
            {
                LogWriter.WriteError("[Line: 39]" + uriFormatException + "\n");

            }
            catch (FileNotFoundException fileNotFoundException)
            {
                LogWriter.Write(
                    "[Line: 43] Bild für User: " + user.FirstName + " " + user.LastName + " konnte nicht gefunden werden.",
                    LogWriter.LogLevel.Warning, this);
                try
                {
                    bild = new BitmapImage();
                    bild.BeginInit();
                    bild.CacheOption = BitmapCacheOption.OnLoad;
                    bild.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                    bild.UriSource = new Uri(UserImagePath + "Default.ico", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //TODO
                    ////log.WriteMessage(ex2.StackTrace);
                    return null;
                }
            }
            return null;

        }

        public BitmapImage GetMessageImage(string downloadUrl)
        {
            
            try
            {
                return DownloadImage(downloadUrl);
            }
            catch (Exception ex)
            {
                Console.WriteLine("----->   " + downloadUrl);
                //TODO
                LogWriter.Write("GetMessageImage" + ex.StackTrace, LogWriter.LogLevel.Error, this);
                try
                {
                    var bild = new BitmapImage();
                    bild.BeginInit();
                    bild.UriSource = new Uri(UserImagePath + "Default.ico", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //TODO
                    ////log.WriteMessage(ex2.StackTrace);
                    return null;
                }
            }

        }
        
        public BitmapImage GetImage(string filename)
        {
            try
            {
                var bild = new BitmapImage();

                bild.BeginInit();
                bild.UriSource = new Uri(UserImagePath + filename,
                                         UriKind.Absolute);
                bild.EndInit();

                return bild;

            }
            catch (Exception ex)
            {
                //TODO
                ////log.WriteMessage(ex.StackTrace);
                try
                {
                    var bild = new BitmapImage();
                    bild.BeginInit();
                    bild.UriSource = new Uri(UserImagePath + "Default.ico", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //TODO
                    ////log.WriteMessage(ex2.StackTrace);
                    return null;
                }
            }

        }
        
        public BitmapImage GetImage(string filename, int width, int height)
        {
            try
            {
                var bild = new BitmapImage();

                bild.BeginInit();
                bild.UriSource = new Uri(UserImagePath + filename,
                                         UriKind.Absolute);
                bild.DecodePixelHeight = height;
                bild.DecodePixelWidth = width;
                bild.EndInit();

                return bild;

            }
            catch (Exception ex)
            {
                //TODO
                ////log.WriteMessage(ex.StackTrace);
                try
                {
                    var bild = new BitmapImage();
                    bild.BeginInit();
                    bild.UriSource = new Uri(UserImagePath + "Default.ico", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //TODO
                    ////log.WriteMessage(ex2.StackTrace);
                    return null;
                }
            }

        }

        public BitmapImage GetProfileImage(Beerdocter beerdocter)
        {
            try
            {
                var bild = new BitmapImage();

                bild.BeginInit();
                bild.UriSource =
                    new Uri(DoctorImagePath + beerdocter.User.FirstName + "_" + beerdocter.User.LastName + ".jpg",
                            UriKind.Absolute);
                
                bild.EndInit();
                return bild;

            }
            catch (Exception ex)
            {
                //TODO
                LogWriter.WriteError("Bierdokterbild nicht gefunden / "+ beerdocter.User.FirstName + "/" + beerdocter.User.LastName);
                try
                {
                    var bild = new BitmapImage();
                    bild.BeginInit();
                    bild.UriSource = new Uri(LogPath + "Beerdocter.jpg", UriKind.Absolute);
                    bild.EndInit();
                    return bild;

                }
                catch (Exception ex2)
                {
                    //TODO
                    LogWriter.WriteMessage("Kein Standardbild für den Bierdokter vorhanden");
                    return null;
                }
            }

        }

        internal BitmapImage DownloadImage(string url)
        {
            var myClient = new WebClient();
            string[] path = url.Split('/');
            if (!File.Exists(MessageImagePath + path[path.Length - 1]))
            {
                myClient.DownloadFile(url, MessageImagePath + path[path.Length - 1]);
                myClient.Dispose();
            }
            BitmapImage pic = new BitmapImage(new Uri(MessageImagePath + path[path.Length - 1]));
            pic.Freeze();
            return pic;
        }
        
        internal void PlaySound(string filename)
        {
            try
            {
                if (_player != null) _player = new SoundPlayer();
                _player.SoundLocation = SoundsPath + filename;
                _player.LoadAsync();
                _player.Play();

            }
            catch (Exception e)
            {
                LogWriter.WriteError("PlaySound(): " + filename + e.StackTrace);
            }
        }

        public void StopPlaying()
        {
            if(_player != null) _player.Stop();
        }

        public enum GameCdSound {Inititate, Countdown, Won, Lost}

        public void PlayGameSound(GameCdSound sound)
        {
            
            switch (sound)
            {
                case GameCdSound.Inititate:
                    PlaySound("cd_initiate.wav");
                    break;
                case GameCdSound.Countdown:
                    PlaySound("cd_countdown.wav");
                    break;
                case GameCdSound.Won:
                    PlaySound("cd_won.wav");
                    break;
                case GameCdSound.Lost:
                    PlaySound("cd_lost.wav");
                    break;
            }
        }

        internal void PlayLiquiditySound(bool p, int soundType)
        {
            PlaySound(p ? "good" + soundType.ToString() +".wav" : "bad.wav");
        }

        private void writeToFile(int i)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter("barrel.txt");

            // write a line of text to the file
            tw.WriteLine(i);

            // close the stream
            tw.Close();
        }

        private int readFromFile()
        {
            // create reader & open file

            try
            {
                TextReader tr = new StreamReader("barrel.txt");
                int a = Convert.ToInt32(tr.ReadLine());
                tr.Close();
                return a;


            }
            catch (Exception e)
            {
                ////log.WriteMessage(e.StackTrace);
            }
            return 0;

        }

        public int GetBarrelStatus()
        {
            return readFromFile();
        }

        public StreamReader ReadLogfile()
        {
            // create reader & open file
            if (File.Exists(LogPath + String.Format(LogWriter.Fileformat, DateTime.Now)))
            {
                return new StreamReader(LogPath + String.Format(LogWriter.Fileformat, DateTime.Now));
            }
            return null;
        }

        internal void DownloadImage(User user)
        {
            
            WebClient myClient = new WebClient();
            Console.WriteLine("Download from " + user.ImagePath + " saving:" + UserImagePath +"test.jpg");
            myClient.DownloadFile(user.ImagePath, UserImagePath + user.FirstName + "_" + user.LastName + ".jpg"); 

            myClient.Dispose();
        }

        
    }
}